package com.zcr.config.etc;

import com.zcr.pojo.Manager;
import com.zcr.pojo.Permission;
import com.zcr.pojo.Role;
import com.zcr.service.ManagerService;
import com.zcr.service.PermissionService;
import com.zcr.service.RoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @author： 张诚
 * @date： 2021-01-29 11:06
 */
@Component
public class DbReam extends AuthorizingRealm {

    @Resource
    private ManagerService managerService;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Manager manager=(Manager) principals.getPrimaryPrincipal();
        List<String> getbypid = permissionService.getbypid(manager.getRoleid());
//        System.out.println(getbypid);
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
        simpleAuthenticationInfo.addStringPermissions(getbypid);
        return simpleAuthenticationInfo;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userCode= (String) token.getPrincipal();
        Manager LoginUser = managerService.loginByManagerName(userCode);
        if(LoginUser == null) return null;
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo
        (LoginUser,
         LoginUser.getPassword(),
         ByteSource.Util.bytes(LoginUser.getUser()+LoginUser.getPassword()),
         super.getName());
        return info;
    }
}
